/*
 * @Author: lyuan2018
 * @Date: 2019-09-03 15:17:16
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-08-20 15:45:25
 * page: 移动到 || 复制到
 */
import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Popover, Tooltip, Button } from 'antd';
import {
  WeaDialog,
  WeaLocaleProvider,
  WeaSearchGroup,
  WeaNewScroll,
} from 'ecCom';
import { RenderForm } from '../emailSetting/util';
import { ValidateForm } from '../../util';

const getLabel = WeaLocaleProvider.getLabel;

@inject('emailContactStore')
@observer
class PopoverMove extends Component {
  constructor(props) {
    super(props);
    this.prefixCls = `${props.wrapCls}-moveCopy`;
    this.state = {
      newVisible: false,
    };
  }

  renderTitle = () => {
    const {
      emailContactStore: { usergroups },
    } = this.props;
    const height = () => {
      if (toJS(usergroups).length > 6) return 200;
      return toJS(usergroups).length * 38;
    };
    return (
      <WeaNewScroll
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaNewScroll@861726`}
        height={height()}
        className={`${this.prefixCls}-container`}
      >
        {toJS(usergroups) &&
          toJS(usergroups).map(item => (
            <div
              key={item.goutId}
              className={`${this.prefixCls}-item`}
              onClick={() => this.moveGroup(item.goutId)}
            >
              <Tooltip
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_Tooltip@tk1w8h@${item.goutId}`}
                title={`${item.groupName} (${item.count})`}
                placement="bottomLeft"
              >
                <div>
                  <span className="groupname">{item.groupName}</span>
                  <span className="count">{`(${item.count})`}</span>
                </div>
              </Tooltip>
            </div>
          ))}
      </WeaNewScroll>
    );
  };

  moveGroup = (groupId) => {
    const {
      emailContactStore: { moveCopyGroup, contactSelect },
      datas: { key },
      onCancel,
    } = this.props;
    let concactIds = toJS(contactSelect)
      .map(v => v.id)
      .join();
    let params = {
      operation: 'moveOrCopyToGroup',
      opt: key,
      concactIds,
      groupId,
    };
    moveCopyGroup(params, () => {
      typeof onCancel === 'function' && onCancel();
    });
  };

  renderContent = () => {
    const {
      datas: { text },
    } = this.props;
    return (
      <div className={`${this.prefixCls}-content`} onClick={this.handleNew}>
        <span className="icon-email-New-group" />
        {text}
      </div>
    );
  };

  handleNew = () => {
    const {
      emailContactStore: { getCondition },
    } = this.props;
    getCondition();
    this.setState({ newVisible: true });
  };

  /* 新建分组 */
  renderNewGroup = () => {
    const { newVisible } = this.state;
    const {
      emailContactStore: { newGroupForm, newGroupFields },
    } = this.props;
    const buttons = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@nka35y@onsave`}
        type="primary"
        onClick={this.saveNewGroup}
      >
        {getLabel(30986, '保存')}
      </Button>,
    ];
    const moreBtn = {
      datas: [
        {
          key: 'save',
          content: getLabel(30986, '保存'),
          disabled: false,
          onClick: this.saveNewGroup,
        },
      ],
      collectParams: {
        favname: getLabel(572, '联系人'),
        favouritetype: 2,
        objid: 0,
        importantlevel: 1,
      },
    };
    return (
      <WeaDialog
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaDialog@fcdz5q`}
        visible={newVisible}
        title={getLabel(30131, '新建分组')}
        icon={'icon-coms-email'}
        iconBgcolor="#a0b0ba"
        className={`${this.prefixCls}-newGroup`}
        style={{ width: 580 }}
        buttons={buttons}
        moreBtn={moreBtn}
        onCancel={this.onCancel}
      >
        {this.getForm(newGroupForm, newGroupFields)}
      </WeaDialog>
    );
  };

  onCancel = () => {
    const {
      emailContactStore: { newGroupForm },
      onCancel,
    } = this.props;
    this.setState({ newVisible: false });
    newGroupForm.resetForm();
    typeof onCancel === 'function' && onCancel();
  };

  // 新建分组并保存
  saveNewGroup = () => {
    const {
      emailContactStore: { newGroupForm, moveCopyGroup, contactSelect },
      datas: { key },
    } = this.props;
    ValidateForm(newGroupForm, () => {
      let concactIds = toJS(contactSelect)
        .map(v => v.id)
        .join();
      let formParams = newGroupForm.getFormParams();
      let params = {
        operation: 'addOrThenMoveOrCopy',
        concactIds,
        opt: key,
        ...formParams,
      };
      moveCopyGroup(params, this.onCancel);
    });
  };

  getForm = (form, fields) => {
    const { isFormInit } = form;
    let group = [];
    isFormInit &&
      fields &&
      fields.map((c) => {
        let items = [];
        c.items.map(field => items.push({ com: RenderForm(form, field) }));
        group.push(
          <WeaSearchGroup
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaSearchGroup@gj3p42@${c.title}`}
            col={1}
            title={c.title}
            needTigger={true}
            showGroup={c.defaultshow}
            items={items}
          />,
        );
      });
    return group;
  };

  render() {
    const { wrapCls, visible } = this.props;
    return (
      <div className={wrapCls}>
        <Popover
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Popover@xd3jns`}
          placement="bottomLeft"
          trigger="click"
          ref="popover"
          overlayClassName={`${wrapCls}-popover`}
          title={this.renderTitle()}
          content={this.renderContent()}
          visible={visible}
        >
          {this.props.children}
        </Popover>
        {this.renderNewGroup()}
      </div>
    );
  }
}

export default PopoverMove;
